﻿using System.Web.Mvc;
using System;
using System.Net;
using smartcrm.Models;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.IO;
using smartcrm.Controllers;

namespace smartcrm.Utilities
{
    public class PermissionAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public string PermissionNo { get; set; }
        public bool IsJson { get; set; }

        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext actionContext)
       {
           if (!string.IsNullOrEmpty(PermissionNo))
           {
               AddAccessLog(actionContext);
               List<string> permissions = (actionContext.HttpContext.Session[BaseController.LOGIN_USER] as LoginUser).PermissionList;
               if (!permissions.Contains(PermissionNo))
               {
                   throw new NoPermissionException(IsJson);
               }
           }
           
        }


        private void AddAccessLog(System.Web.Mvc.ActionExecutingContext actionContext)
        {
            string FilePath = Path.Combine( actionContext.HttpContext.Server.MapPath("/"), "log");
            FilePath = Path.Combine(FilePath, "access");
            DateTime dt = DateTime.Now;
            String FileName = Path.Combine(FilePath, dt.ToString("yyyyMMdd") + ".txt"); 
            try
            {
                string controllerName = actionContext.RouteData.Values.ContainsKey("controller") ? actionContext.RouteData.Values["controller"].ToString() : "";
                string actionName = actionContext.RouteData.Values.ContainsKey("action") ? actionContext.RouteData.Values["action"].ToString() : "";
            
                System.IO.File.AppendAllText(FileName, 
                    string.Format("{0} {1} {2}/{3}{4}", dt.ToString("HH:mm:ss"), actionContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"],controllerName,actionName, System.Environment.NewLine));
            }
            catch
            {
            }
        }

    }

    public class NoPermissionException : Exception
    {
        public bool IsJson { get; set; }
        public NoPermissionException(bool isJson)
        {
            IsJson = isJson;
        }
    }

    public class NoEntityFound : Exception
    {
 
    }
}
